﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace NCommonLib.Thread
{
    public class CancellationTokenFactory
    {
        #region Sigleton

        private static CancellationTokenFactory _instance;

        private CancellationTokenFactory()
        {

        }

        public static CancellationTokenFactory Instance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new CancellationTokenFactory();
                }
                return _instance;
            }
        }

        #endregion

        #region Fields

        private Dictionary<string, CancellationTokenSource> _sourceDic = new Dictionary<string, CancellationTokenSource>();

        #endregion

        #region Method

        public CancellationTokenSource GetCancelToken(string tokenTag)
        {
            CancellationTokenSource _source;
            if (_sourceDic.Keys.Contains(tokenTag))
            {
                _sourceDic.TryGetValue(tokenTag, out _source);
            }
            else
            {
                _source = new CancellationTokenSource();
                _sourceDic.Add(tokenTag, _source);
            }
            return _source;
        }

        #endregion
    }
}
